<?php

namespace App\Http\Controllers\QH_Api;

use App\Http\Controllers\TK_Api\ApiBaseController;
use App\Jobs\UserKsDayRankJob;
use App\Jobs\UserLearnQuestionCountOfTodayRankJob;
use App\Jobs\UserLearnQuestionCountRankJob;
use App\Models\CourseColumn;
use App\Models\NetCourse;
use App\Models\Qh_Banner;
use App\Models\Qh_KaoshiResult;
use App\Models\Qh_MiniProgramComponent;
use App\Models\TQ_Config;
use App\Models\User;
use App\Service\Redis\RedisBaseService;
use Auth;
use Carbon\Carbon;
use DB;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Cache;

class CommonController extends ApiBaseController
{
    public function getProvinceList() {
        $list = \DB::table('area')->where('pid', 0)->selectRaw('id, name, pinyin')->get();

        foreach ($list as $item) {
            $item->pinyin = [$item->pinyin];
        }

        return $this->restful($list);
    }

    /**
     * 获取首页配置
     * @return JsonResponse|object
     */
    public function getHomeConfig(RedisBaseService $redisBaseService) {
        // 获取首页配置
        $config = $redisBaseService->getPageConfig('config:homePageConfig');
        $valueJson = json_decode($config);
        $valueJson->banner = Qh_Banner::whereIn('id', $valueJson->banner)->get();
        $valueJsonComponents = $valueJson->components;
        $components = [];
        $componentsSorts = array();
        foreach ($valueJsonComponents as $key => $row) {
            $componentsSorts[$key] = $row->sort;
        }
        array_multisort($componentsSorts, SORT_ASC, $valueJsonComponents);

        foreach ($valueJsonComponents as $component) {
            $c = Qh_MiniProgramComponent::find($component->id);
            if (!$c) continue;
            $c->data = qhMiniProgramComponentDataFormat($c);
            $components[] = $c;
        }

        $valueJson->components = $components;

        // 获取分享数据
        $globalConfig = TQ_Config::where('key', 'global_config')->first();
        $shareInfo = [
            'title' => null,
            'image' => null
        ];
        if ($globalConfig) {
            $j = json_decode($globalConfig->value);
            if ($j->shareTitle) $shareInfo['title'] = $j->shareTitle;
            if ($j->shareImage) $shareInfo['image'] = $j->shareImage;
        }
        $valueJson->shareInfo = $shareInfo;

        // 弹窗广告数据
        $alertAdsInfo = [
            'enable' => false,
            'showRate' => null,
            'image' => null,
            'jumpTarget' => null,
            'jumpType' => null,
            'jumpParams' => null
        ];
        if ($globalConfig) {
            if (!empty($j->alert_ads_enable)) $alertAdsInfo['enable'] = $j->alert_ads_enable;
            if (!empty($j->alert_ads_show_rate)) $alertAdsInfo['showRate'] = $j->alert_ads_show_rate;
            if (!empty($j->alert_ads_image)) $alertAdsInfo['image'] = $j->alert_ads_image;
            if (!empty($j->alert_ads_jump_target)) $alertAdsInfo['jumpTarget'] = $j->alert_ads_jump_target;
            if (!empty($j->alert_ads_jump_type)) $alertAdsInfo['jumpType'] = $j->alert_ads_jump_type;
            if (!empty($j->alert_ads_jump_params)) $alertAdsInfo['jumpParams'] = $j->alert_ads_jump_params;
        }
        $valueJson->alertAdsInfo = $alertAdsInfo;

        return $this->restful($valueJson);
    }

    public function getInitConfig() {
        // 获取学科价格是否显示的开关
        $config = TQ_Config::where('key', 'global_config')->first();
        $coursePriceShowEnable = true;
        $paymentEnable = true;
        if ($config) {
            $configValue = json_decode($config->value, true);
            $coursePriceShowEnable = $configValue['course_price_enable'] ?? true;
            $paymentEnable = $configValue['payment_enable'] ?? true;
            $wx_video = !empty($configValue['wx_video']) ? $configValue['wx_video'] : [
                'finderUserName' => null,
                'channelEnabled' => false,
                'liveEnabled' => false,
            ];
        }

        return $this->restful([
            'coursePriceShowEnable' => $coursePriceShowEnable,
            'paymentEnable' => $paymentEnable,
            'wx_video' => [
                'finderUserName' => $wx_video['finderUserName'],
                'channelEnabled' => $wx_video['channelEnabled'],
                'liveEnabled' => $wx_video['liveEnabled'],
            ],
        ]);
    }

    /**
     * 获取网课页配置
     * @return JsonResponse|object
     * @throws \RedisException
     */
    public function getWangkeConfig() {
        $config = TQ_Config::where('key', 'wangke_config')->first();
        if (!$config) {
            $config = new TQ_Config(['key' => 'wangke_config', 'value' => json_encode([
                'banner' => [],
                'textList' => null,
                'longBanner' => [],
                'components' => [],
                'headerBackgroundImage' => null,
                'pageMode' => 1,
                'cheatImage' => null,
            ])]);
        }

        $valueJson = json_decode($config->value);
        $valueJson->banner = Qh_Banner::whereIn('id', $valueJson->banner)->get();
        $textList = Qh_MiniProgramComponent::find($valueJson->textList);
        if ($textList) {
            $valueJson->textList = json_decode($textList->data, true);
        }
        $valueJson->longBanner = Qh_Banner::whereIn('id', $valueJson->longBanner)->get();

        $valueJsonComponents = $valueJson->components;
        $components = [];
        $componentsSorts = array();
        foreach ($valueJsonComponents as $key => $row) {
            $componentsSorts[$key] = $row->sort;
        }
        array_multisort($componentsSorts, SORT_ASC, $valueJsonComponents);

        foreach ($valueJsonComponents as $component) {
            $c = Qh_MiniProgramComponent::find($component->id);
            if (!$c) continue;
            $c->data = qhMiniProgramComponentDataFormat($c);
            $components[] = $c;
        }
        $valueJson->components = $components;

        if (Auth::guard('api')->check()) {
            $user = Auth::guard('api')->user();
            $netCourseStat = [
                'minuteOfToday' => $user->netCourseLearnOfLastTime ? (Carbon::make($user->netCourseLearnOfLastTime)->isToday() ? $user->netCourseLearnMinuteOfToday : 0) : 0,       // 今日学习分钟数
                'hourOfAll' => round($user->netCourseLearnMinute / 60),           // 总学习小时数
                'learnDays' => ($user->netCourseLearnMinute > 0 && round($user->netCourseLearnMinute / 60 / 24) < 1) ? 1 : round($user->netCourseLearnMinute / 60 / 24),           // 学习天数
                'learnSection' => $user->learnVideoSectionDoneCount,        // 已学小节
                'allSection' => $user->learnVideoSectionCount,          // 所有小节
            ];
        }else {
            $netCourseStat = [
                'minuteOfToday' => 0,       // 今日学习分钟数
                'hourOfAll' => 0,           // 总学习小时数
                'learnDays' => 0,           // 学习天数
                'learnSection' => 0,        // 已学小节
                'allSection' => 0,          // 所有小节
            ];
        }
        $valueJson->netCourseStat = $netCourseStat;

        $statistics = [
            'daysCount' => 0,
            'countdown' => 0,
            'questionCount' => 0,
            'questionCountOfToday' => 0,
        ];
        //if (Auth::guard('api')->check()) {
        //    $user = Auth::guard('api')->user();
        //    // 坚持天数
        //    $statistics['daysCount'] = $user->ksDaysCount ?? 0;
        //    // 倒计时
        //    $statistics['countdown'] = $user->ksCountdown ? Carbon::now()->diffInDays(Carbon::make($user->ksCountdown)) : 0;
        //    // 刷题数量
        //    $statistics['questionCount'] = DB::table('qh_user_learn_question_logs')->where('userId', $user->id)->count();
        //    // $statistics['questionCountOfToday'] =  DB::table('qh_user_learn_question_logs')->where('userId', $user->id)->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])->count();
        //    $statistics['questionCountOfToday'] =  $user->learnQuestionOfLastTime ? (Carbon::parse($user->learnQuestionOfLastTime)->isToday() ? $user->learnQuestionCountOfToday : 0) : 0;
        //}
        $valueJson->statistics = $statistics;

        // 获取省份下网课详情列表
        $valueJson->netCourseList = NetCourse::where('province', 'like', '%'.request('province', '全国').'%')->get();

        return $this->restful($valueJson);
    }

    public function getKaoshiConfig() {
        $config = TQ_Config::where('key', 'kaoshi_config')->first();
        if (!$config) {
            $config = new TQ_Config(['key' => 'kaoshi_config', 'value' => json_encode([
                'components' => []
            ])]);
            $config->save();
        }

        $valueJson = json_decode($config->value);
        $valueJsonComponents = $valueJson->components;
        $components = [];
        $componentsSorts = array();
        foreach ($valueJsonComponents as $key => $row) {
            $componentsSorts[$key] = $row->sort;
        }
        array_multisort($componentsSorts, SORT_ASC, $valueJsonComponents);

        foreach ($valueJsonComponents as $component) {
            $c = Qh_MiniProgramComponent::find($component->id);
            if (!$c) continue;
            $c->data = qhMiniProgramComponentDataFormat($c);
            $components[] = $c;
        }
        $valueJson->components = $components;

        return $this->restful($valueJson);
    }

    /**
     * 排行榜
     * @return JsonResponse|object
     */
    public function getRank() {
        // 今日刷题量，总刷题量，坚持天数(1,2,3)
        // 默认今日刷题量

        $cacheMinutes = 10;

        // 按坚持天数排序
        if (request('sort', 1) == 3) {
            // $list = User::whereNotNull('ksDaysCount')->orderByDesc('ksDaysCount')->limit(15)->get();

            // 加到缓存里
            $rankLastTime = \Cache::get('rank_3_last_time');
            $rankLastData = \Cache::get('rank_3_last_data');

            if ($rankLastData && $rankLastTime && Carbon::createFromTimestamp($rankLastTime)->diffInMinutes(Carbon::now()) < $cacheMinutes) {
                $list = $rankLastData;
            }else {
                $list = DB::table('user')->whereNotNull('ksDaysCount')->orderByDesc('ksDaysCount')->limit(15)->get();
                foreach ($list as $item) {
                    $rate = 0;
                    $rightCount = 0;
                    $wrongCount = 0;
                    $qLogs = DB::table('qh_user_question_logs')->where('userId', $item->id)->get();
                    foreach ($qLogs as $log) {
                        if ($log->result == 1) $rightCount +=1;
                        if ($log->result == 2) $wrongCount +=1;
                    }
                    $sum = $rightCount + $wrongCount;
                    if ($sum > 0) {
                        $rate = round($rightCount / $sum, 2);
                    }
                    $item->questionRate = $rate;
                    // $item->learnQuestionCountOfToday = DB::table('qh_user_learn_question_logs')->where('userId', $item->id)->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])->count();
                    $item->learnQuestionCountOfToday = $item->learnQuestionOfLastTime ? (Carbon::createFromTimestamp($item->learnQuestionOfLastTime)->isToday() ? $item->learnQuestionCountOfToday : 0) : 0;
                }

                \Cache::put('rank_3_last_time', time());
                \Cache::put('rank_3_last_data', $list);

            }
        }
        // 按总刷题量排序
        elseif (request('sort', 1) == 2) {
            // 加到缓存里
            $rankLastTime = \Cache::get('rank_2_last_time');
            $rankLastData = \Cache::get('rank_2_last_data');

            if ($rankLastData && $rankLastTime && Carbon::createFromTimestamp($rankLastTime)->diffInMinutes(Carbon::now()) < $cacheMinutes) {
                $list = $rankLastData;
            }else {
                $userIds = DB::table('qh_user_learn_question_logs')
                    ->selectRaw('userId, COUNT(*) as count')
                    ->groupBy('userId')
                    ->orderByDesc('count')
                    ->limit(15)
                    ->pluck('userId')
                    ->toArray();

                $list = User::select([
                    'id',
                    'avatar',
                    'nickname'
                ])->whereIn('id', $userIds)->get()->sortBy(function ($user) use ($userIds) {
                    return array_search($user->id, $userIds);
                })->values();

                \Cache::put('rank_2_last_time', time());
                \Cache::put('rank_2_last_data', $list);
            }
        }
        // 按今日刷题量排序
        else {
            // 加到缓存里
            $rankLastTime = \Cache::get('rank_1_last_time');
            $rankLastData = \Cache::get('rank_1_last_data');

            if ($rankLastData && $rankLastTime && Carbon::createFromTimestamp($rankLastTime)->diffInMinutes(Carbon::now()) < $cacheMinutes) {
                $list = $rankLastData;
            }else {
                $userIds = DB::table('qh_user_learn_question_logs')
                    ->selectRaw('userId, COUNT(*) as count')
                    ->whereBetween('created_at', [Carbon::now()->startOfDay(), Carbon::now()->endOfDay()])
                    ->groupBy('userId')
                    ->orderByDesc('count')
                    ->limit(15)
                    ->pluck('userId')
                    ->toArray();

                $list = User::whereIn('id', $userIds)->get()->sortBy(function ($user) use ($userIds) {
                    return array_search($user->id, $userIds);
                })->values();

                \Cache::put('rank_1_last_time', time());
                \Cache::put('rank_1_last_data', $list);
            }
        }

        return $this->restful($list);
    }
    public function getRankV2(RedisBaseService $redisBaseService) {
        // 今日刷题量，总刷题量，坚持天数(1,2,3)
        // 默认今日刷题量

        // UserLearnQuestionCountRankJob::dispatchSync();
        // UserLearnQuestionCountOfTodayRankJob::dispatchSync();
        // UserKsDayRankJob::dispatchSync();

        // 按坚持天数排序
        if (request('sort', 1) == 3) {
            $cache = $redisBaseService->getUserKsDayRank();
            if (!$cache) UserKsDayRankJob::dispatchSync();
        }
        // 按总刷题量排序
        elseif (request('sort', 1) == 2) {
            $cache = $redisBaseService->getUserLearnQuestionCountRank();
            if (!$cache) UserLearnQuestionCountRankJob::dispatchSync();
        }
        // 按今日刷题量排序
        else {
            $cache = $redisBaseService->getUserLearnQuestionOfTodayCountRank();
            if (!$cache) UserLearnQuestionCountOfTodayRankJob::dispatchSync();
        }
        return $this->restful($cache ?: []);
    }

    /**
     * 获取考试排行榜
     * @return JsonResponse|object
     */
    public function getKaoshiRank($knowledgeId) {
        $list = Qh_KaoshiResult::selectRaw('qh_kaoshi_results.*, user.nickname, user.avatar')
             ->where('knowledgeId', $knowledgeId)
            ->join('user', 'qh_kaoshi_results.userId', '=', 'user.id')
            ->groupBy('qh_kaoshi_results.userId')
            ->orderByDesc('qh_kaoshi_results.score')
            ->orderBy('qh_kaoshi_results.seconds')
            ->limit(15)
            ->get();

        return $this->restful($list);
    }

    public function getKaoshiRank1() {
        $list = Qh_KaoshiResult::selectRaw('qh_kaoshi_results.*, user.nickname, user.avatar')
            ->where('knowledgeId', $knowledgeId)
            ->join('user', 'qh_kaoshi_results.userId', '=', 'user.id')
            ->groupBy('qh_kaoshi_results.userId')
            ->orderByDesc('qh_kaoshi_results.score')
            ->orderBy('qh_kaoshi_results.seconds')
            ->limit(15)
            ->get();

        return $this->restful($list);
    }
}
